package com.sixdog.regulate.cmdService;

import com.sixdog.regulate.bean.CmdResult;
import com.sixdog.regulate.utils.StringUtils;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.ArrayList;
@Service
public class CmdUtils{

    //执行完关闭会话
    public static final String EXECUTE_TYPE_ONCE = "once";
    //维持会话
    public static final String EXECUTE_TYPE_MAINTAIN = "maintain";
    //快速执行（特点：不读取返回信息，不执行流操作）
    public static final String EXECUTE_TYPE_FAST = "fast";

    /*
    * 执行命令并返回执行后的结果
    * */
    private String location;

    public CmdUtils() {
        location = StringUtils.readFileContent("../config/adbPath.config");
    }

    //普通执行命令
    public CmdResult execute(StringBuilder command){
        //String [] cmd={"cmd","/C","copy exe1 exe2"};
        StringBuilder cmd=  new StringBuilder().append("cmd /C ").append(location).append(command);
        return executeCmd(cmd);
    }
    //带属性执行（见常量）
    public CmdResult execute(StringBuilder command,String type){
        switch (type){
            case EXECUTE_TYPE_MAINTAIN : {
                StringBuilder cmd=  new StringBuilder().append("cmd /K ").append(location).append(command);
                return executeCmd(cmd);
            }
            case EXECUTE_TYPE_FAST : {
                StringBuilder cmd=  new StringBuilder().append(location).append(command);
                System.out.println(cmd);
                try {
                    Process proc = Runtime.getRuntime().exec(cmd.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            default: {
                return execute(command);
            }
        }
    }
    //直接执行cmd
    public CmdResult executeCmd(StringBuilder cmd){
        //新建cmd执行后的返回对象
        CmdResult cmdResult = new CmdResult(cmd);

        try {
            //执行命令
            Process proc =Runtime.getRuntime().exec(cmd.toString());

            //取得命令结果的输出流
            InputStream fis=proc.getInputStream();
            //用一个读输出流类去读
            InputStreamReader isr=new InputStreamReader(fis);
            //用缓冲器读行
            BufferedReader br=new BufferedReader(isr);

            //返回对象的属性Lines
            ArrayList<String> lines = new ArrayList<>();
            String line;
            //直到读完为止
            while((line=br.readLine())!=null)
            {
//                System.out.println(br.readLine());
                lines.add(line);
            }
            cmdResult.setLines(lines);
        }catch (Exception e){
            e.printStackTrace();
        }
        cmdResult.setStatusMessage("完成");
        return cmdResult;
    }

    //连续执行多次
    public CmdResult continuityExecute(StringBuilder command,int durationMS, int intervalMS){
        StringBuilder cmd=  new StringBuilder("cmd /C ").append(location).append(command);
        Process proc = null;
        //计时开始
        long startTime = System.currentTimeMillis();
        //预计结束时间
        long expectedEndTime = startTime+durationMS;
        //执行命令
        try {

            long l = System.currentTimeMillis();

            long sleepTime;
            while (l<=expectedEndTime){
                proc = Runtime.getRuntime().exec(cmd.toString());
                try {
                    sleepTime = intervalMS - (System.currentTimeMillis() - l);
                    if (sleepTime<0) sleepTime=0;
                    Thread.sleep(sleepTime);
//                    proc.waitFor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //执行一个循环后的时间戳
                l = System.currentTimeMillis();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //计时结束
        long usedTime = System.currentTimeMillis()-startTime;
        CmdResult cmdResult = new CmdResult(cmd);
        if (proc!=null){
            //取得命令结果的输入流
            InputStream fis=proc.getInputStream();
            //用一个读输出流类去读
            InputStreamReader isr=new InputStreamReader(fis);
            //用缓冲器读行
            BufferedReader br=new BufferedReader(isr);
            //返回对象的属性Lines
            ArrayList<String> lines = new ArrayList<>();
            String line;
            //直到读完为止
            try {
                while ((line=br.readLine())!=null) {
                    lines.add(line);
                }
                cmdResult.setLines(lines);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        cmdResult.setStatusMessage("用时 "+usedTime+"毫秒 ");
        return cmdResult;
    }
    //同时执行多条命令
    public CmdResult manyExecute(ArrayList<StringBuilder> commands){
        StringBuilder cmd=  new StringBuilder();
        for (int i=0;i<commands.size();i++){
            if (i==0){
                cmd.append(commands.get(i));
            }else {
                cmd.append(" && ").append(commands.get(i));
            }
        }
        CmdResult cmdResult = execute(cmd);
        return cmdResult;
    }

}
